package org.teemor.demo.zookeeper.simple;

import ch.qos.logback.core.net.server.Client;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.teemor.demo.zookeeper.factory.ClientFactory;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/2/19
 */
public class SimpleWatcherDemo {
    private String workerPath = "/test/listener/remoteNode";
    private String subWorkerPath = "/test/listener/remoteNode/id-";
    private String connectionString = "common.teemor.xyz:2181";

    public static void main(String[] args) throws Exception {
        SimpleWatcherDemo simpleDemo = new SimpleWatcherDemo();
        simpleDemo.testWatcher();

    }
    public void testWatcher() throws Exception{
        CuratorFramework client = ClientFactory.createSimple(connectionString);
        client.start();
        boolean isExist = client.checkExists().forPath(workerPath) != null;
        if ( ! isExist) {
            client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(workerPath, null);
        }
        //watcher是一次性的，当监听了一次事件后，该watcher就失效了，如果需要再次监听，则需要反复注册watcher
        Watcher watcher = new Watcher() {

            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("监听到的变化为：" + watchedEvent);
                try {
                    client.getData().usingWatcher(this).forPath(workerPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        byte[] content = client.getData().usingWatcher(watcher).forPath(workerPath);
//        System.out.println("监听内容为：" + new String(content));
        Thread.sleep(Integer.MAX_VALUE);
    }
}
